<!--
 * @Author: wangding
 * @Date: 2020-10-22 17:14:47
 * @LastEditTime: 2021-02-18 17:38:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \solaxcloud\src\views\system\role\add.vue
-->
<template>
    <div class="site-bind-wifisn-main-box">
        <el-dialog
            :title="$t('site.siteLinkWifiSn')"
            :visible="visibleBind"
            width="900px"
            @close="()=>{$store.commit('setVisibleBind',false)}">
            <el-form ref="form" :model="form" label-width="180px" >
                <el-row :gutter="24">
                    <el-col :span="18">
                        <template v-for="(item, index) in form.wifiSNdata" >
                            <el-form-item 
                                :key="item.key" 
                                :label="$t('devWifi.wifiSN')+(index==0?'':index+1)" 
                                :prop="'wifiSNdata.'+index+'.wifiSN'"
                                :rules="[{ required: true, message: $t('index_js_notNull')},{ validator:test_wifiSN, trigger:'blur'}]" >
                                    <el-input v-big v-model="item.wifiSN" :placeholder="$t('devWifi.wifiSN')+(index==0?'':index+1)"></el-input>
                                    <el-tooltip effect="light" class="icon-nmi" placement="right">
                                        <div slot="content" style="width:200px;">
                                            <img src="../../assets/img/wifiMessage.png" alt="" width="100%">
                                        </div>
                                        <i class="el-icon-question iconClass"></i>
                                    </el-tooltip>
                                    <i class="el-icon-circle-plus-outline" @click="add()" btn-add></i>
                                    <!-- <i class="el-icon-remove-outline" @click="remove(index)" btn-remove v-if="index!=0"></i> -->
                                    <!-- <el-button class="button-batch-pos" type="primary" @click="save('form')">{{$t('site.relate_wifiSN_batch')}}</el-button> -->
                                    <el-upload
                                        class="upload button-batch-pos"
                                        :action="url"
                                        :on-preview="handlePreview"
                                        :on-remove="handleRemove"
                                        :before-remove="beforeRemove"
                                        :data="uploadData"
                                        :limit="1"
                                        :on-exceed="handleExceed"
                                        :on-success="onsuccess"
                                        :headers='{token:token}'
                                        :file-list="file"
                                        :show-file-list='false'
                                        >
                                        <el-button size="small" type="primary">{{$t('site.relate_wifiSN_batch')}}</el-button>
                                    </el-upload>
                            </el-form-item>
                            <el-form-item :key="index">
                                <el-input v-model="item.remark" :placeholder="$t('devWifi.note')+(index==0?'':index+1)"></el-input>
                                <el-button class="button-download-pos"  @click="download">{{$t('download.templates')}}</el-button>
                            </el-form-item>
                        </template>
                    </el-col>
                </el-row>
            </el-form>
            <el-divider></el-divider>
            <baseTable v-loading="loading"  row-key='sid' :data="dataRows" border  stripe   :column='column' :select='false' :current='current' :size='size'>
                <template #enableFlag="{data}">
                    <span :style='data.isOnline==1?"color:#429dff":""'>
                        <i class="iconfont icon-wifi" style="vertical-align: middle;" ></i>
                        {{returnStatus(data.isOnline)}}
                    </span>
                </template>
                <template #deviceType="{data}">
                        {{comm.returnCode(data.moduleType==1?textDataList.WIFI_DEVICE_TYPE:textDataList.WIFI_DEVICE_CHARGE_TYPE,data.deviceType,'value','code')}}
                </template>
                <template #option="{data}">
                    <div class="option-box">
                        <el-button size='small' type="primary" icon="el-icon-crop"  @click='wifiUnbundlingWifiSN(data)'  :title='$t("devWifi.unbundling")'></el-button>
                    </div>
                </template>
            </baseTable>
            
            <div style="overflow: hidden;">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="current"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="()=>{$store.commit('setVisibleBind',false)}">{{$t('cancel')}}</el-button>
                    <el-button type="primary" @click="$store.commit('setVisibleBind',false)">{{$t('save')}}</el-button>
                </span>
        </el-dialog>
    </div>
</template>

<script>
import baseTable from '../../components/common/baseTable'
export default {
    components: {
        baseTable
    },
    props: {
        selRow:''
    },
    data() {
        this.test_wifiSN = async(rule, value, callback) => {
            let res = await this.API.checkWifiSNByUser({
                wifiSn:value,
                userIds:this.selRow.userIds,
                siteId:this.selRow.ids
            })
            if (res == '2') {
                callback(new Error(this.$t('login.js_sign_wifisn_error')));
            }else if (res == '3') {
                callback(new Error(this.$t('login.js_sign_wifisn_registered')));
            }else{
                callback();
            }
        }
        return {
            loading:false,
            url:'',
            url_download:'',
            form:{
                wifiSNdata:[{
                    wifiSN: '',
                    packageId:'',
                    remark: '',
                    key: Date.now()
                }]
            },
            uploadData:{
                siteId:'',
                userId:'',
                domain:''
            },
            file:[],
            dataRows:[],
            column:[{
                title: this.$t('devWifi.wifiSN'),
                value: 'wifiSN',
                slot: 'wifiSN'
            },{
                title: this.$t('devWifi.deviceType'),
                value: 'deviceType',
                slot: 'deviceType'
            },{
            //     title: this.$t('site.inverterNum'),
            //     value: 'moduleNum'
            // },{
                title: this.$t('bind.time'),
                value: 'bindTime'
            },{
                title: this.$t('device.inverter.enableFlag'),
                value: 'isOnline',
                slot: 'enableFlag',
            },{
                title: this.$t('remark'),
                value: 'note',
            },{
                title: this.$t('control'),
                slot: 'option',
            }],
            size:10,
            current:1,
            total:1,
            textDataList:{}
        };
    },
    computed: {
        visibleBind(){
            return this.$store.state.sysStore.visibleBind
        },
        token(){
            return sessionStorage.getItem('token')
        }
    },
    watch: {
        selRow:{
            handler(nv,ov){
                this.uploadData={
                    siteId:this.selRow.ids,
                    userId:this.selRow.userIds,
                    domain:window.location.host
                }
                if(nv){
                    this.getDictionaryBatch()
                    
                }
                this.file=[]
            },
            deep:true,
            immediate:true
        }
    },
    created() {

    },
    mounted() {
        this.url=process.env.VUE_APP_BASE_API2+'/site/siteLinkWifiSnBatch'
        this.url_download=process.env.VUE_APP_BASE_API2+'/site/downLoadTemplate'
    },
    methods: {
        async wifiUnbundlingWifiSN(data){
            let res = await this.API.wifiUnbundlingWifiSN({
                ids:data.ids
            })
            if(this.comm.showMsg(res.success)){
                this.siteGetSiteWifiSNPage()
            }
        },
        async getDictionaryBatch(){
            this.loading = true
            let res = await this.API.getDictionaryBatch({
                dictCodes:'ON_LINE_STATE,INVERTER_TYPES,IS_PUBLIC,SALER_TYPE,INTELBARS_INVERTER_TYPES,WIFI_DEVICE_TYPE,WIFI_DEVICE_CHARGE_TYPE',
                lang:localStorage.getItem('lan') || 'zh_CN'
            })
            this.textDataList = res || {}
            this.loading = false
            this.siteGetSiteWifiSNPage()
        },
        returnStatus(flag){
            let code = ''
            if(!this.textDataList){
                return
            }
            this.textDataList.ON_LINE_STATE.forEach(item =>{
                if(item.value == flag){
                    code = item.code
                }
            })
            return code
        },
        async siteGetSiteWifiSNPage(){
            this.loading = true
            let res = await this.API.siteGetSiteWifiSNPage({
                siteId:this.selRow.ids,
                current:this.current,
                size:this.size,
            })
            this.loading = false
            this.dataRows = res.rows
            this.total = res.total
        },
        handleSizeChange(val) {
          this.size = val
          this.current = 1
          this.siteGetSiteWifiSNPage()
        },
        handleCurrentChange(val) {
          this.current = val
          this.siteGetSiteWifiSNPage()
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(this.$t('file-choose-msg1')+` ${files.length} ${this.$t('file-choose-msg2')} ${files.length + fileList.length}${this.$t('file-choose-msg3')} `);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`${this.$t('confirm-remove')} ${ file.name }？`);
        },
        onsuccess(res, file, fileList){
            if(res.success){
                this.siteGetSiteWifiSNPage()
                this.$message.success(this.$t('site.sn_binding_success'))
            }else{
                this.$message.warning(this.$t('site.js_relate_fail'))
            }
            console.log(res)
            console.log(file)
            console.log(fileList)
        },
        download(){
            this.comm.windowOpen('/site/downLoadTemplate')
        },
        handleDownload(item) {
            let elemIF = document.createElement("iframe");
            elemIF.src = `${this.url_download}`;
            elemIF.style.display = "none";
            document.body.appendChild(elemIF);
        },
        add(){
            // this.form.wifiSNdata.push({
            //     wifiSN: '',
            //     packageId:'',
            //     remark: '',
            //     key: Date.now()
            // });
            this.save('form')
        },
        // remove(index){
        //     this.form.wifiSNdata.splice(index,1)
        // },
        save(formName){
            this.$refs[formName].validate((valid) => {
              if (valid) {
                  this.submit()
              } else {
                console.log('error submit!!');
                return false;
              }
            });
        },
        async submit(){
            let wifiSNs=[],remarks=[],packageIds=[]
            this.form.wifiSNdata.forEach(item => {
                wifiSNs.push(item.wifiSN)
                remarks.push(item.remark||'-')
                packageIds.push(item.packageId||'-')
            });
            let res = await this.API.bindSiteWifiSN({
                wifiSN:wifiSNs.join(),
                packageIds:packageIds.join(),
                notes:remarks.join(' --split-- '),
                siteId:this.selRow.ids,
                domain:window.location.host,
                updateTime:this.$options.filters['dateFormat'](new Date())
            })
            if(res.success){
                this.siteGetSiteWifiSNPage()
                this.$message.success(this.$t('index.control_success'));
            }else{
                this.$message.error(this.$t('index.control_fail'));
            }
            // this.$store.commit('setVisibleBind',false)
            this.$emit('uploadPage',true)
        }
    },
};
</script>

<style  lang="less">
    .site-bind-wifisn-main-box{
        .el-dialog{
                margin-top: 4vh !important;
        }
        [btn-add],[btn-remove]{
            position: absolute;
            right: -40px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 24px;
            color: #828282;
            cursor: pointer;
            &:hover{
                color: #e6a300;
            }
        }
        .iconClass{
            margin-top: -3px;
            font-size: 16px;
            color: #666;
            vertical-align: middle;
        }
        [btn-add]{
            right: -40px;
        }
        [btn-remove]{
            right: -80px;
        }
        .button-batch-pos{
            position: absolute;
            right: -180px;
            top: 0px;
        }
        .button-download-pos{
            position: absolute;
            right: -160px;
            top: 0px;
        }
    }
    
</style>
